import React, { Component } from 'react'
import {
    View,
    StyleSheet,
    Text,
    ScrollView,
    Image,
    Platform,
    ImageBackground,
    DeviceEventEmitter
} from 'react-native'
import NavBar from 'src/components/navBar'
import IdentifyProgress from '../components/IdentityProgress'
import UploadIdCard from '../components/UploadIdCard'
import UploadTips from '../components/UploadTips'
import Input from '../components/Input'
import { deviceHeight, deviceWidth, changeId } from "src/util"
import ActionSheet from 'react-native-actionsheet'
import { uploadCardImage } from "src/service/Auth"
import ImagePicker from 'react-native-image-crop-picker'
import Layer from "src/components/Layer"
import { inject } from "mobx-react/native"
import navigationhelper from "src/components/navigationhelper"
import Divider from "src/components/Divider"
import { Flex } from '@ant-design/react-native';
import WeChatPay from '../../../service/Home'
import * as WeChat from 'react-native-wechat';
import PayWayView from './components/payWayView'
import Alipay from 'react-native-yunpeng-alipay';
import Svg, {
    G,
    Path,
    LinearGradient,
    RadialGradient,
  } from 'react-native-svg';

@inject('userAuth')
export default class MemberCenter extends Component<{}> {
    constructor(props) {
        super(props)
        this.state = {
            isreFresh: false,
            show: this.props.userAuth.currentUser.level == 1 ? true : false,
            level: this.props.userAuth.currentUser.level,
        }
    }
    componentWillMount() {

    }

    getWechatpay = (payType) => {
        WeChatPay.fetchWecahtPay({
            token: this.props.userAuth.token,
            pay_type: payType
        }).then((res) => {
            if (res.status == 'success') {
                if(payType == 1){
                    this.wechatPay(res.data)
                }
                else{
                    Alipay.pay(res.data).then(function(res){
                            if (res.resultStatus == '9000'){
                                this.props.userAuth.fetchCurrentUserInfo({token:this.props.userAuth.token})
                                Layer.showMsg('支付成功')
                            }else {
                                Layer.showMsg('支付失败')
                            }
                        }, function (err) {
                            Layer.showMsg('取消支付')
                        });
                    
                }
            }
        }).catch((error) => {
            Layer.showMsg(error.message)
        })

    }

    wechatPay = (dict) => {
        WeChat.isWXAppInstalled().then((isInstalled) => {
            if (isInstalled) {
                WeChat.pay({
                    partnerId: dict.partnerid,  // 商家向财付通申请的商家id
                    prepayId: dict.prepayid,   // 预支付订单
                    nonceStr: dict.noncestr,   // 随机串，防重发
                    timeStamp: dict.timestamp,  // 时间戳，防重发.
                    package: dict.package,    // 商家根据财付通文档填写的数据和签名
                    sign: dict.sign,       // 商家根据微信开放平台文档对数据做的签名
                }).then((requestJson) => {
                    console.log(requestJson)
                    //支付成功回调                                           
                    if (requestJson.errCode == "0") {
                        this.regModal.showOrDismiss(false)
                        this.props.userAuth.fetchCurrentUserInfo({ token: this.props.userAuth.token })
                        this.setState({
                            show: false,
                            level: 2
                        })
                        setTimeout(function () {
                            DeviceEventEmitter.emit('refreshUserInfo')
                        }, 1000);
                        //回调成功处理
                    }
                }).catch((err) => {
                    Layer.showMsg('取消支付')
                })
            } else {
                Layer.showMsg('请先安装微信')
            }
        });
    }

    commonCell = (title, content) => {
        return (
            <View style={{ marginLeft: 20, marginRight: 20, marginTop: 20 }}>
                <Text style={{ color: '#378EFB', fontSize: 14 }}>{title}</Text>
                <Text style={{ color: '#8E8E93', fontSize: 13, marginTop: 10 }}>{content}</Text>
            </View>
        )

    }

    render() {
        const { avatar,child} = this.props.userAuth.currentUser
        let total = child.directLevel1Child + child.directLevel2Child + child.directLevel3Child
        const { level } = this.state

        if(total >= 20){
            total = 20;
        }
        // console.log('total',total)
        return (
            <View style={{ flex: 1 }}>
                <NavBar
                    back={() => { navigationhelper.goBack() }}
                    title="会员中心"
                    barStyle={'dark-content'}
                />
                <ScrollView style={{ backgroundColor: '#fff'}}>
                    <ImageBackground
                        resizeMode='stretch'
                        style={{ width: deviceWidth, height: 210, alignItems: 'center' }}
                        source={require('src/assets/mine/huiyuanzhongxin.png')}
                    >

                        <Image
                            defaultSource={require('src/assets/mine/userDefaultAvatar.png')}
                            source={{ uri: avatar }} style={{ height: 42, width: 42, borderRadius: 21, marginTop: 40 }}>
                        </Image>
                        <Text style={{ color: '#fff', fontSize: 12, marginTop: 10 }}>{level == 1 ? '普通用户' : level == 2 ? 'VIP用户' : '白金用户'}</Text>

                    <Svg 
                         style={{marginTop:20}}
                         height="24" width={210}>
 
                     <G fill="none" stroke="#3d5875">
                      <Path  strokeLinecap="round" strokeWidth="8" d="M5 8 l200 0" />
                      </G>
                      {total>0?   <G fill="none" stroke="#00e0ff">
                      <Path strokeLinecap="round" strokeWidth="8" d={`M5 8 l${total*10} 0`} />
                       </G>:null}
                       </Svg>
                    {total<20?<Text style={{color:'#fff',fontSize:10}}>   再邀请 {20-total} 位用户, 即可免费升级为会员</Text>:null}
                    </ImageBackground>

                    <View style={{ marginTop: 10, marginLeft: 20, flexDirection: 'row' }}>
                        <View style={{ backgroundColor: '#378EFB', width: 3, height: 18, marginTop: 1.5 }}></View>
                        <Text style={{ color: '#2E2E2E', marginLeft: 10, fontSize: 17 }}>普通VIP</Text>
                    </View>

                    <View style={{ flexDirection: 'column' }}>
                        <View style={{ marginLeft: 20, marginRight: 20, marginTop: 20 }}>
                            <Text style={{ color: '#378EFB', fontSize: 14 }}>升级方式</Text>
                            <Text style={{ color: '#8E8E93', fontSize: 13, marginTop: 10, lineHeight: 20 }}>1、当邀请人数达到20人并且都实名认证后，系统将自动升级为VIP会员</Text>
                            <Text style={{ color: '#8E8E93', fontSize: 13, marginTop: 10, lineHeight: 20 }}>2、成功缴费178元，无需邀请20人，也可升级成为VIP会员</Text>
                        </View>
                        <View style={{ marginLeft: 20, marginRight: 20, marginTop: 20 }}>
                            <Text style={{ color: '#378EFB', fontSize: 14 }}>升级优势</Text>
                            <Text style={{ color: '#8E8E93', fontSize: 13, marginTop: 10, lineHeight: 20 }}>1、费率直降万5降低手续费</Text>
                            <Text style={{ color: '#8E8E93', fontSize: 13, marginTop: 10, lineHeight: 20 }}>2、增加万5的固定分润，增加收益</Text>
                        </View>
                    </View>

                    {this.state.show ? <Flex style={styles.button} onPress={() => {
                        this.regModal.showOrDismiss(true)
                    }}>
                        <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 16 }}>升级付费</Text>
                    </Flex> : null}
                    <View style={{height:100,backgroundColor:'#fff'}}/>
                </ScrollView>

                <PayWayView
                    isVisible={false}
                    ref={i => this.regModal = i}
                    close={() => {
                        this.regModal.showOrDismiss(false)
                    }}
                    weChat={() => {
                        this.regModal.selectedPayWay(0)
                    }}
                    aliPay={() => {
                        this.regModal.selectedPayWay(1)
                    }}

                    payMoney={(payWay) => {
                        if (payWay == 0) {
                            this.getWechatpay(1)
                            this.regModal.showOrDismiss(false)
                            // this.wechatPay()
                        }
                        else {
                            this.getWechatpay(2)
                            this.regModal.showOrDismiss(false)
                        }
                    }}
                />
            </View>
        )
    }
}
const styles = StyleSheet.create({
    button: {
        flex: 1,
        height: 50,
        borderRadius: 8,
        backgroundColor: '#378EFB',
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: 16,
        marginTop: 50
    },

})